package com.sumfun.blog.controller;

import com.sumfun.blog.annotation.RequireLogin;
import com.sumfun.blog.common.BaseResponse;
import com.sumfun.blog.common.ErrorCode;
import com.sumfun.blog.common.ResultUtils;
import com.sumfun.blog.exception.BusinessException;
import com.sumfun.blog.model.domain.Files;
import com.sumfun.blog.service.FilesService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.Resource;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URLEncoder;
 
@Controller
public class FileDownloadController {

    private static final String FILE_DIRECTORY = "/path/to/upload/directory/";
    @Value("${file.upload.path}")
    private String uploadDirPath;

    @Autowired
    private FilesService filesService;

    @GetMapping("/download/{id:.+}")
    @ResponseBody
    public BaseResponse<Boolean> downloadFile(@PathVariable Long id, HttpServletResponse response) {
        if(id == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }

        Files files = filesService.getById(id);
        String fileName = files.getFileName();
        String filePath = files.getFilePath();
        try {
            // 读到流中
            InputStream inputStream = new FileInputStream(filePath);// 文件的存放路径
            response.reset();
            response.setContentType("application/octet-stream");
            response.addHeader("Content-Disposition", "attachment; filename=" + URLEncoder.encode(fileName, "UTF-8"));
            ServletOutputStream outputStream = response.getOutputStream();
            byte[] b = new byte[1024];
            int len;
            //从输入流中读取一定数量的字节，并将其存储在缓冲区字节数组中，读到末尾返回-1
            while ((len = inputStream.read(b)) > 0) {
                outputStream.write(b, 0, len);
            }
            inputStream.close();
            return ResultUtils.success(true);
        } catch (IOException ex) {
            ex.printStackTrace();
            return ResultUtils.error(ErrorCode.SYSTEM_ERROR);
        }
    }


    @GetMapping("/file/{id:.+}")
    @ResponseBody
    public BaseResponse<Files> getFile(@PathVariable Long id) {
        if(id == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        Files files = filesService.getById(id);
        return ResultUtils.success(files);
    }
}